package main

import (
	//"fmt"
	"github.com/playnb/mustang/global"
	"github.com/playnb/mustang/log"
	"github.com/playnb/mustang/nosql"
	//"github.com/playnb/mustang/sqldb"
	"github.com/playnb/mustang/utils"
	"github.com/playnb/mustang/weixin"
	//"math/rand"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

//UserAuthorized 授权成功
func UserAuthorized(state string, token *weixin.WebAccessToken, w http.ResponseWriter, r *http.Request) bool {
	param := ""
	strs := strings.Split(state, "$")
	if len(strs) > 0 {
		state = strs[0]
		if len(strs) > 1 {
			for i := 1; i < len(strs); i++ {
				param = param + "&" + strs[i]
			}
			param = "&" + param
		}
	}
	values, err := url.ParseQuery(param)
	if err != nil {
		log.Error(err.Error())
		return true
	}

	shareOpenID := ""
	if len(values["shareOpenID"]) > 0 {
		shareOpenID = values["shareOpenID"][0]
	}
	log.Trace("分享人: %s", shareOpenID)

	userinfo := weixin.GetUserInfoBySNS(token.AccessToken, token.OpenID, false)
	if userinfo != nil {
		log.Trace("App: %s 有人授权了name: %s", state, userinfo.NikeName)

		loginKey := userinfo.OpenID + "&" + strconv.FormatInt(time.Now().Unix(), 10)
		log.Debug("密钥 %s", global.C.SecretKey)
		loginKey, _ = utils.AesEncryptString(loginKey, global.C.SecretKey)

		//redis写入准备登陆
		loginVaildTime := time.Second * time.Duration(global.C.LoginTimeOut)
		loginVaildTime = time.Hour * 1
		log.Dev("loginKey: %s", loginKey)
		err = nosql.Redis.Set("Login:"+loginKey, userinfo.OpenID, loginVaildTime).Err()
		if err != nil {
			log.Error("Redis Error: %s", err.Error())
		}

		nosql.Redis.SAdd("ST:TOTAL_VIEW", userinfo.OpenID)
		nosql.Redis.Incr("ST:VIEW_PAGE")

		wxHttpParams := &utils.WinXinHttpParams{}
		wxHttpParams.OpenID = token.OpenID
		wxHttpParams.Pic = userinfo.HeadImgUrl
		wxHttpParams.ServerToken = loginKey
		wxHttpParams.Token = token.AccessToken
		wxHttpParams.UserName = userinfo.NikeName

		// 分享好友处理
		if len(shareOpenID) > 0 && userinfo.OpenID != shareOpenID {
			k1 := "Friends:" + shareOpenID
			//k2 := "Friends:" + userinfo.OpenID
			if !nosql.Redis.HExists(k1, userinfo.OpenID).Val() {
				/*
					err = nosql.Redis.SAdd(k1, userinfo.OpenID).Err()
					if err != nil {
						log.Error("Redis Error: %s", err.Error())
					}

					err = nosql.Redis.SAdd(k2, shareOpenID).Err()
					if err != nil {
						log.Error("Redis Error: %s", err.Error())
					}
				*/

				err = nosql.Redis.SAdd("NewFriend:"+shareOpenID, userinfo.OpenID).Err()
				if err != nil {
					log.Error("Redis Error: %s", err.Error())
				}

				err = nosql.Redis.SAdd("NewFriend:"+userinfo.OpenID, shareOpenID).Err()
				if err != nil {
					log.Error("Redis Error: %s", err.Error())
				}

			}
			shareinfo := weixin.GetUserInfo(shareOpenID, true)
			if shareinfo != nil {
				wxHttpParams.ShareName = shareinfo.NikeName
			}
		}

		hStr, _ := wxHttpParams.Encode(global.C.SecretKey, false)
		rUrl := "http://" + global.C.ServiceDomain + "/apps/" + state + "/SC_" + hStr
		log.Debug("%s", rUrl)
		http.Redirect(w, r, rUrl, http.StatusFound)
	}
	/*
		userinfo := &weixin.WeiXinUserInfo{}
		key := "OpenID:" + token.OpenID
		ret, err := nosql.Redis.Get(key).Result()
		if err != nil {
			userinfo = weixin.GetUserInfo(token.OpenID, true)
			if userinfo != nil {
				jStr,_ := json.Marshal(userinfo)
				_, err = nosql.Redis.Set(key, string(jStr), 0).Result()
				if err != nil {
					log.Debug(err.Error() + " | " + ret)
				} else {
					log.Trace("App: %s 有人授权了(new)name: %s", state, userinfo.NikeName)
				}
			}
		} else {
			err = json.Unmarshal([]byte(ret), userinfo)
			if err!=nil{
				log.Error(err.Error())
				return true
			}
			log.Trace("App: %s 有人授权了name: %s", state, userinfo.NikeName)
		}
	*/

	return true
}
